package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.UserService;
import com.xuanzheng.company.service.impl.UserServiceImpl;
import com.xuanzheng.company.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/deleteManagerAccount")
public class DeleteManagerAccountServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    private Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        // 获取当前登录用户
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            out.print(gson.toJson(result));
            return;
        }

        User currentUser = (User) session.getAttribute("user");
        
        // 验证用户是否是公司负责人
        if (currentUser.getRole() != 1) {
            result.put("success", false);
            result.put("message", "只有公司负责人可以使用此功能");
            out.print(gson.toJson(result));
            return;
        }

        // 检查用户是否已经创建了公司
        if (currentUser.getCompanyId() != null && !currentUser.getCompanyId().isEmpty()) {
            result.put("success", false);
            result.put("message", "已创建公司的负责人请使用注销公司功能");
            out.print(gson.toJson(result));
            return;
        }

        System.out.println("开始处理公司负责人账号注销请求 - 用户ID: " + currentUser.getId() + ", 姓名: " + currentUser.getName());

        try {
            // 执行注销账号操作（包括删除相关申请记录）
            boolean success = deleteManagerAccountAndApplications(currentUser.getId());
            
            if (success) {
                System.out.println("公司负责人账号删除成功 - 用户ID: " + currentUser.getId());
                // 注销成功，销毁会话
                session.invalidate();
                
                result.put("success", true);
                result.put("message", "账号已成功注销，您的账号信息及相关申请记录已被删除");
                result.put("redirect", "index.html"); // 重定向到登录页
            } else {
                System.out.println("公司负责人账号删除失败 - 用户ID: " + currentUser.getId());
                result.put("success", false);
                result.put("message", "注销账号失败，请稍后重试");
            }
        } catch (Exception e) {
            System.err.println("注销公司负责人账号过程发生异常: " + e.getMessage());
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "注销账号失败: " + e.getMessage());
        }

        out.print(gson.toJson(result));
    }

    private boolean deleteManagerAccountAndApplications(String userId) {
        Connection conn = null;
        boolean success = false;
        
        try {
            System.out.println("开始删除公司负责人账号及相关记录，用户ID=" + userId);
            conn = DBUtil.getConnection();
            conn.setAutoCommit(false);
            
            // 1. 删除公司申请记录（如果有的话）
            deleteCompanyApplications(conn, userId);
            System.out.println("已删除公司申请记录");
            
            // 2. 删除用户的公司员工记录（如果有的话）
            deleteCompanyEmployeeRecords(conn, userId);
            System.out.println("已删除公司员工记录");
            
            // 3. 删除用户账号
            deleteUserAccount(conn, userId);
            System.out.println("已删除用户账号");
            
            // 提交事务
            conn.commit();
            success = true;
            System.out.println("公司负责人账号注销成功完成");
            
        } catch (SQLException e) {
            e.printStackTrace();
            System.err.println("公司负责人账号注销失败，错误: " + e.getMessage());
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        } finally {
            if (conn != null) {
                try {
                    conn.setAutoCommit(true);
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        
        return success;
    }
    
    // 删除公司申请记录
    private void deleteCompanyApplications(Connection conn, String userId) throws SQLException {
        PreparedStatement pstmt = null;
        
        try {
            // 删除所有与此用户相关的公司申请记录
            String sql = "DELETE FROM company WHERE manager_id = ? AND status != 1";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, userId);
            int deletedRows = pstmt.executeUpdate();
            System.out.println("删除了 " + deletedRows + " 条公司申请记录");
        } finally {
            if (pstmt != null) pstmt.close();
        }
    }
    
    // 删除公司员工记录
    private void deleteCompanyEmployeeRecords(Connection conn, String userId) throws SQLException {
        PreparedStatement pstmt = null;
        
        try {
            // 删除所有与此用户相关的公司员工记录
            String sql = "DELETE FROM company_employee WHERE user_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, userId);
            int deletedRows = pstmt.executeUpdate();
            System.out.println("删除了 " + deletedRows + " 条公司员工记录");
        } finally {
            if (pstmt != null) pstmt.close();
        }
    }
    
    // 删除用户账号
    private void deleteUserAccount(Connection conn, String userId) throws SQLException {
        PreparedStatement pstmt = null;
        
        try {
            String sql = "DELETE FROM user WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, userId);
            int deletedRows = pstmt.executeUpdate();
            System.out.println("删除了 " + deletedRows + " 个用户账号");
        } finally {
            if (pstmt != null) pstmt.close();
        }
    }
}